<template>
  <div
    v-loading="loading"
    class="main_form">
    <el-form
      ref="aiWriteFormId"
      :model="ruleForm"
      :rules="formRules"
      inline
      label-width="80px"
      label-position="top"
      style="padding-right: 15px;"
      class="ai_form_box"
    >
      <div
        v-for="(config, pIndex) in configFormList"
        :key="config.title + pIndex"
      >
        <aiTitle :title="config.title" />
        <div class="form_content">
          <el-form-item
            v-for="(info, index) in config.itemList"
            :key="info.prop + index"
            :label="info.label"
            :prop="info.prop"
            :label-width="info.labelWidth || '80px'"
          >
            <el-input
              v-if="info.comp === 'input'"
              v-model.trim="ruleForm[info.prop]"
              :title="ruleForm[info.prop]"
              :type="info.type || 'text'"
              :placeholder="info.placeholder || ''"
              :rules="info.rule || {}"
              :rows="info.rows || 5"
              :show-word-limit="false"
              style="width: 100%;"
              size="small"
              resize="none"
              clearable
            />
            <flex
              v-if="info.tagList"
              align="center"
              wrap="wrap"
            >
              <el-tag
                v-for="(title, index) in info.tagList"
                :key="index"
                type="info"
                class="tag_box"
                @click="handleAddTitle(title)"> {{ title }} </el-tag>
            </flex>
            <!-- 控制有权限单位 控制领导讲话显示或者不显示 -->
            <el-select
              v-if="info.comp === 'select'&&info.default!=='致辞'"
              v-model="ruleForm[info.prop]"
              :rules="info.rule || {}"
              :filterable="info.filterable"
              :allow-create="info.allowCreate"
              :disabled="info.disabled"
              :placeholder="info.placeholder || ''"
              style="width: 100%;"
              size="small"
              clearable
              @change="handleChangeType($event, info.prop)"
            >
              <el-option
                v-for="(item, index) in info.optionList"
                :key="index"
                :value="item.name"
                :label="item.name"
              />
            </el-select>
            <el-select
              v-if="info.comp === 'select'&&info.default==='致辞'"
              v-model="ruleForm[info.prop]"
              :rules="info.rule || {}"
              :filterable="info.filterable"
              :allow-create="info.allowCreate"
              :disabled="info.disabled"
              :placeholder="info.placeholder || ''"
              style="width: 100%;"
              size="small"
              clearable
              @change="handleChangeType($event, info.prop)"
            >
            <!-- v-for="(item, index) in isHaspremision?info.optionList:info.optionList.slice(0,1)" -->
              <el-option
                v-for="(item, index) in info.optionList"
                :key="index"
                :value="item.name"
                :label="item.name"
              />
            </el-select>
            <el-date-picker
              v-if="info.comp === 'date-picker'"
              v-model="ruleForm[info.prop]"
              :editable="false"
              :type="info.type"
              :disabled="info.disabled"
              :value-format="info.valueFormat"
              :placeholder="info.placeholder"
              style="width: 100%;"
              size="small"
              clearable
            />
            <div v-if="info.comp === 'upload'">
              <input
                id="aiUploadFileId"
                type="file"
                accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                style="display: none;"
                @change="uploadTemplate($event)"/>
              <el-button
                type="primary"
                size="mini"
                plain
                @click="handleUploadFile(info)"
              >
                上传文件
              </el-button>
              <div
                slot="label"
                class="ai-form-desc">{{ info.desc }}</div>
              <flex
                v-for="file in ruleForm[info.aliasProp]"
                :key="file.id"
                align="center"
                justify="between"
                class="upload_box"
              >
                <span
                  :title="file.fileName"
                  class="upload_name">{{ file.fileName }}</span>
                <span :class="['upload_btn', {'upload_success': fileBtnText === '解析完成'}]">{{ fileBtnText }}</span>
              </flex>
            </div>
          </el-form-item>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import * as api from '@/api/writing'
import aiTitle from './aiTitle.vue'

export default {
  components: { aiTitle },
  props: {
    configFormList: {
      type: Array,
      default: () => []
    },
    configFormData: {
      type: Object,
      default: () => {}
    },
    formRules: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      loading: false,
      fileBtnText: '',
      tempFile: {},
      ruleForm: {}
    }
  },
  watch: {
    configFormList () {
      this.$set(this, 'ruleForm', {...this.ruleForm, ...this.configFormData})
      this.$nextTick(() => {
        this.$refs.aiWriteFormId.clearValidate()
      })
    }
  },
  computed:{
    //是否有权限
    isHaspremision() {
     let ax_compid = window.Application.PluginStorage.getItem('ax_compid');
     if (ax_compid && (ax_compid === '1' || ax_compid === 'f5b9d842-2d9f-4a87-9dfc-ad7465c86422')) {
        return true;
      } else {
        return false
      }
    }
  },
  mounted () {
    this.$set(this, 'ruleForm', this.configFormData)
    this.$nextTick(() => {
      this.$refs.aiWriteFormId.clearValidate()
    })
  },
  methods: {
    handleChangeType (value, name) {
      name === 'document_type' && this.$emit('change', value)
    },
    handleUploadFile (upload) {
      this.tempFile = upload
      document.getElementById('aiUploadFileId').click()
    },
    uploadTemplate (event) {
      let files = event.target.files || event.srcElement.files
      let template = files[0]
      let flag = template.name.endsWith('.doc') || template.name.endsWith('.docx')
      if (!flag) {
        this.$message.error('请上传正确的文档!')
        document.getElementById('aiUploadFileId').value = null
        return
      }
      let formData = new FormData()
      formData.append('file', template)
      this.loading = true
      api.aiUploadWordFile(formData).then(res => {
        const data = res.data
        this.$set(this.ruleForm, this.tempFile.aliasProp, [data])
        this.$set(this.ruleForm, this.tempFile.formData, formData)
        this.$nextTick(() => {
          this.handleParse() // 自动解析
        })
      }).finally(() => {
        this.loading = false
        document.getElementById('aiUploadFileId').value = null
      })
    },
    handleParse () {
      this.fileBtnText = '正在解析'
      api.aiAnalysisWordFile(this.ruleForm.formData).then(res => {
        let data = res.data
        if (data.length > 1000) {
          data = data.slice(0, 1000) // 截取前千个字符
        }
        this.$set(this.ruleForm, this.tempFile.prop, data)
      }).finally(() => {
        this.fileBtnText = '解析完成'
      })
    },
    handleAddTitle (title) {
      this.$set(this.ruleForm, 'document_title', title)
    },
    handleConfirm () {
      let validFlag = false
      this.$refs.aiWriteFormId.validate((valid) => {
        validFlag = valid
      })
      return validFlag
    },
    handleSubmit () {
      let transform = {}
      this.configFormList.map(item => {
        item.itemList.map(el => {
          transform[el.label] = this.ruleForm[el.prop]
        })
      })
      return {
        aiData: transform,
        formData: this.ruleForm
      }
    }
  }
}
</script>

<style scoped>
.main_form {
  height: 100%;
  padding: 0 10px 10px;
  box-sizing: border-box;
}
.ai_form_box.el-form >>> .el-form-item__label {
  height: 30px;
}
.ai_form_box.el-form >>> .el-input__inner {
  background-color: #FAFAFA;
}
.ai_form_box.el-form >>> .el-input.is-active .el-input__inner {
  background-color: #FFF;
}
.ai_form_box.el-form >>> .el-input__inner:focus {
  background-color: #FFF;
}
.ai_form_box.el-form >>> .el-textarea__inner {
  font-family: Arial;
  background-color: #FAFAFA;
}
.ai_form_box.el-form >>> .el-textarea__inner:focus {
  background-color: #FFF;
}
.form_content {
  margin-top: 1px;
  margin-left: 1px;
  margin-bottom: 1px;
  padding: 10px;
  border-radius: 4px;
  background-color: #FFF;
  box-shadow: 0 0 4px 0 rgba(0, 0, 0, .2);
}
.ai-form-desc {
  color: #909199;
  font-size: 12px;
}
.el-form .el-form-item {
  width: 100%;
}
.tag_box {
  cursor: pointer;
  margin-top: 10px;
  margin-right: 10px;
}
.upload_box {
  padding: 0 10px;
  box-sizing: border-box;
  background-color: #FAFAFA;
}
.upload_name {
  width: calc(100% - 54px);
  font-size: 12px;
  color: #303133;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.upload_btn {
  width: 54px;
  font-size: 12px;
  color: #3C88FF;
}
.upload_success {
  color: #67C23A;
}
</style>
